import { _decorator, Component, Node, director, game } from 'cc';
import { IModule } from './BaseModule';
import { GameEvent } from '../../../game/configs/GameEvent';
import { EventSystem } from '../EventSystem';
import { ResourceSystem } from '../ResourceSystem';
import { NetworkSystem } from '../NetworkSystem';
import { UIManager } from '../UIFramework';
import { HotUpdateSystem } from '../HotUpdateSystem';
import { AudioSystem } from '../AudioSystem';
import { LogSystem } from '../LogSystem';
import { ProcessSystem } from '../ProcessSystem';
import { GamePlayState, GameResultState, LaunchState, MainMenuState } from '../../../game/Flows/GameState';
import { GameState } from '../../../game/configs/GameState';
const { ccclass, property } = _decorator;

@ccclass('GameFramework')
export class GameFramework extends Component {
    private static _instance: GameFramework | null = null;
    private modules: Map<string, IModule> | null = null;

    static get instance(): GameFramework {
        if (!this._instance) {
            // 查找场景中的实例
            const scene = director.getScene();
            if (scene) {
                const frameworkNode = scene.getChildByName('GameFramework');
                if (frameworkNode) {
                    this._instance = frameworkNode.getComponent(GameFramework);
                }

                // 如果场景中没有找到实例，则创建一个新的
                if (!this._instance) {
                    const newNode = new Node('GameFramework');
                    this._instance = newNode.addComponent(GameFramework);
                    if (this._instance) {
                        scene.addChild(newNode);
                        console.log('GameFramework: Created new instance');
                    } else {
                        console.error('GameFramework: Failed to create instance');
                    }
                }
            } else {
                console.warn('GameFramework: No active scene found, instance creation delayed');
                return null as any; // 返回 null，但类型仍为 GameFramework 以避免类型错误
            }
        }
        return this._instance!;
    }

    onLoad() {
        if (GameFramework._instance != null && GameFramework._instance != this) {
            this.destroy();
            return;
        }

        GameFramework._instance = this;
        director.addPersistRootNode(this.node);
        this.modules = new Map<string, IModule>();
        this.initFramework();
        this.setupGlobalErrorHandler();
    }

    update(dt: number) {
        if (GameFramework._instance != this)
            return;
        // 每帧更新逻辑可以放在这里
        // 或者通过事件系统分发到其他模块
         GameFramework.event?.emit(GameEvent.GAME_UPDATE, dt);
    }

    lateUpdate(dt: number): void {
        if (GameFramework._instance != this)
            return;
         GameFramework.event?.emit(GameEvent.GAME_LATEUPDATE, dt);
    }

    onDestroy() {
        // 框架销毁时进行清理
        if (GameFramework._instance != this)
            return;

        // 通知各系统进行资源释放
        GameFramework.event.emit(GameEvent.GAME_DESTORY);

        GameFramework.log.debug("Game Framework destroyed");

        // 关闭所有已注册的模块
        this.shutdownAllModules();

        this.RemoveAllModules();

        GameFramework._instance = null;
    }

    // 定义系统实例，使用懒加载模式
    private _eventSystem: EventSystem | null = null;
    private _resourceSystem: ResourceSystem | null = null;
    private _networkSystem: NetworkSystem | null = null;
    private _uiManager: UIManager | null = null;
    private _hotUpdateSystem: HotUpdateSystem | null = null;
    private _audioSystem: AudioSystem | null = null;
    private _logSystem: LogSystem | null = null;
    private _processSystem: ProcessSystem | null = null;

    // 提供获取各个系统的公共方法，实现解耦
    public static get event(): EventSystem {
        if (!GameFramework.instance._eventSystem) {
            GameFramework.instance._eventSystem = new EventSystem();
            GameFramework.instance.registerModule(GameFramework.instance._eventSystem);
        }
        return GameFramework.instance._eventSystem;
    }

    public static get resource(): ResourceSystem {
        if (!GameFramework.instance._resourceSystem) {
            GameFramework.instance._resourceSystem = new ResourceSystem();
            GameFramework.instance.registerModule(GameFramework.instance._resourceSystem);
        }
        return GameFramework.instance._resourceSystem;
    }

    public static get network(): NetworkSystem {
        if (!GameFramework.instance._networkSystem) {
            GameFramework.instance._networkSystem = new NetworkSystem();
            GameFramework.instance.registerModule(GameFramework.instance._networkSystem);
        }
        return GameFramework.instance._networkSystem;
    }

    public static get ui(): UIManager {
        if (!GameFramework.instance._uiManager) {
            GameFramework.instance._uiManager = new UIManager();
            GameFramework.instance.registerModule(GameFramework.instance._uiManager);
        }
        return GameFramework.instance._uiManager;
    }

    public static get hotUpdate(): HotUpdateSystem {
        if (!GameFramework.instance._hotUpdateSystem) {
            GameFramework.instance._hotUpdateSystem = new HotUpdateSystem();
            GameFramework.instance.registerModule(GameFramework.instance._hotUpdateSystem);
        }
        return GameFramework.instance._hotUpdateSystem;
    }

    public static get audio(): AudioSystem {
        if (!GameFramework.instance._audioSystem) {
            GameFramework.instance._audioSystem = new AudioSystem();
            GameFramework.instance.registerModule(GameFramework.instance._audioSystem);
        }
        return GameFramework.instance._audioSystem;
    }

    public static get log(): LogSystem {
        if (!GameFramework.instance._logSystem) {
            GameFramework.instance._logSystem = new LogSystem();
            GameFramework.instance.registerModule(GameFramework.instance._logSystem);
        }
        return GameFramework.instance._logSystem;
    }

    public static get process(): ProcessSystem {
        if (!GameFramework.instance._processSystem) {
            GameFramework.instance._processSystem = new ProcessSystem();
            GameFramework.instance.registerModule(GameFramework.instance._processSystem);
        }
        return GameFramework.instance._processSystem;
    }

    private initFramework() {
        console.log("Game Framework initialized");
        // GameFramework.event.emit("GAME_FRAMEWORK_INIT");
 
        // 添加状态到流程系统
        GameFramework.process.addProcessState(new LaunchState());
        GameFramework.process.addProcessState(new MainMenuState());
        GameFramework.process.addProcessState(new GamePlayState());
        GameFramework.process.addProcessState(new GameResultState());
 
        // 启动游戏流程
        GameFramework.process.startProcess(GameState.Launch);
    }

    private setupGlobalErrorHandler() {
        // 全局错误处理
        // game.on(game.EVENT_ENGINE_INITED, () => {
        //     console.log("Cocos Engine initialized");
        // });

        // game.on(game.EVENT_GAME_INITED, () => {
        //     console.log("Game initialized");
        // });

        // 添加全局未捕获异常处理
        // window.addEventListener('error', (event) => {
        //     console.error('Global error caught:', event.error);
        //     // 可以在这里添加错误上报或其他处理逻辑
        //     GameFramework.event.emit('GLOBAL_ERROR', event.error);
        //     return true; // 防止默认处理
        // });

        // 处理Promise未捕获的rejection
        // window.addEventListener('unhandledrejection', (event) => {
        //     console.error('Unhandled promise rejection:', event.reason);
        //     GameFramework.event.emit('UNHANDLED_REJECTION', event.reason);
        //     return true; // 防止默认处理
        // });
    }

    /**
     * 注册模块
     * @param module 模块实例
     */
    private registerModule<T extends IModule>(module: IModule): T {
        if (this.modules.has(module.uid)) {
            GameFramework.log.debug("模块已存在");
            throw new Error("模块已存在");
        }
        module.init();
        this.modules.set(module.uid, module);
        return module as T;
    }

    /**
     * 卸载模块
     * @param module 模块实例
     */
    private unregisterModule(module: IModule): void {
        if (this.modules.has(module.uid)) {
            module.shutdown();
            this.modules.delete(module.uid);
        }
    }

    private RemoveAllModules(): void {
        this.modules.clear();
    }
    
    /**
     * 关闭所有模块
     */
    private shutdownAllModules(): void {
        this.modules.forEach(module => {
            module.shutdown();
            GameFramework.log.debug(`模块${module.uid}已关闭`);
        });
    }

    addChild(layer: Node) {
        if (!layer || !(layer instanceof Node)) {
            console.error('GameFramework.addChild: Invalid node parameter');
            return;
        }
        this.node.addChild(layer);
    }
}